<template>
  <div class="face-manage">
    <el-button link type="primary" @click="showDialog = true">
      {{ buttonText || '人脸管理' }}
    </el-button>

    <teleport to="body">
      <el-dialog v-model="showDialog" destroy-on-close :title="title || '人脸管理'" width="50%" @close="handleClose">
        <div v-loading="loading" class="face-list">
          <div v-if="faceList.length > 0" class="face-grid">
            <div v-for="(face, index) in faceList" :key="index" class="face-item">
              <el-image fit="cover" :src="face.url" />
              <div class="face-actions">
                <el-button link type="danger" @click="handleDelete(face)">删除</el-button>
              </div>
            </div>
          </div>
          <el-empty v-else description="暂无人脸照片" />
        </div>

        <div class="upload-section">
          <el-upload :before-upload="beforeUpload" class="face-upload" :http-request="customUpload" :show-file-list="false">
            <el-button type="primary">上传人脸照片</el-button>
          </el-upload>
        </div>

        <template #footer>
          <span class="dialog-footer">
            <el-button @click="handleClose">关闭</el-button>
          </span>
        </template>
      </el-dialog>
    </teleport>
  </div>
</template>

<script setup lang="ts">
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, watch } from 'vue'
import { deleteFace, getFaceList, registerFace } from '/@/api/faceRecognition'
import request from '/@/utils/request'

interface ApiResponse<T = any> {
  code: number
  message?: string
  result?: T
}

interface OssResponse {
  url: string
  name: string
  status: number
  message: string
}

interface FaceInfo {
  id: number
  userId: string
  faceUserInfo: string | null
  faceGroupId: string
  faceUserId: string
  faceImage: string | null
  faceToken: string
  createdAt: string
  updatedAt: string
  url?: string
  imgUrl?: string
}

defineOptions({
  name: 'FaceManage',
})

interface Props {
  id: string
  buttonText?: string
  title?: string
}

const props = defineProps<Props>()

// 状态管理
const showDialog = ref(false)
const loading = ref(false)
const faceList = ref<FaceInfo[]>([])

// 获取人脸列表
const fetchFaceList = async () => {
  loading.value = true
  try {
    const response = await getFaceList(props.id)
    const data = response as any
    if (data.code === 0 && data.result) {
      faceList.value = data.result.map((face: FaceInfo) => ({
        ...face,
        url: face.imgUrl || undefined,
      }))
    }
  } catch (error) {
    console.error('获取人脸列表失败:', error)
    ElMessage.error('获取人脸列表失败')
  } finally {
    loading.value = false
  }
}

// 删除人脸照片
const handleDelete = async (face: FaceInfo) => {
  try {
    await ElMessageBox.confirm('确定要删除这张人脸照片吗?', '提示', {
      type: 'warning',
    })

    const response = await deleteFace({
      faceId: face.faceUserId,
      userId: props.id,
    })

    const data = response as any
    if (data.code === 0) {
      ElMessage.success('删除成功')
      fetchFaceList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 上传前验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 10

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 10MB!')
    return false
  }
  return true
}

// 自定义上传
const customUpload = async (options: any) => {
  try {
    // 首先上传到OSS
    const ossFormData = new FormData()
    ossFormData.append('file', options.file)

    const ossResponse = await request({
      url: '/api/ossPut',
      method: 'post',
      data: ossFormData,
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    const ossData = ossResponse as any
    if (!ossData?.url) {
      throw new Error('OSS上传失败')
    }

    // 使用OSS返回的URL注册人脸
    const response = await registerFace({
      faceImage: ossData.base64Image,
      imgUrl: ossData.url,
      userId: props.id,
    })

    const data = response as any
    if (data?.code === 0) {
      ElMessage.success('上传成功')
      fetchFaceList()
    } else {
      throw new Error(data?.message || '注册失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '上传失败')
  }
}

// 关闭弹窗
const handleClose = () => {
  showDialog.value = false
}

// 监听弹窗显示状态
watch(
  () => showDialog.value,
  (newVal) => {
    if (newVal) {
      fetchFaceList()
    }
  }
)
</script>

<style scoped lang="scss">
.face-manage {
  display: inline-block;
}

.face-list {
  min-height: 200px;
  margin-bottom: 20px;
}

.face-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 20px;
  padding: 20px 0;
}

.face-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;

  .el-image {
    width: 100%;
    height: 150px;
    display: block;
  }

  .face-actions {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 8px;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
  }

  &:hover .face-actions {
    opacity: 1;
  }
}

.upload-section {
  border-top: 1px solid #eee;
  padding-top: 20px;
  text-align: center;
}
</style>
